Introduction to Open Data Science - Course Project

About the project

Write a short description about the course and add a link to your GitHub repository here. This is an R Markdown (.Rmd) file so you should use R Markdown syntax.

# This is a so-called "R chunk" where you can write R code.

date()
## [1] "Fri Nov 26 19:41:18 2021"

I heard from my colleague about the Introduction to Open Data Science. She warmly recommended the course which is why I signed up for autumn term 2021.

I am looking forward to learning more about open data science and best practice for data analysis in order to make my work easily accessible and readable for my colleagues.


Week 2: Regression and model validation

Describe the work you have done this week and summarize your learning.

date()
## [1] "Fri Nov 26 19:41:18 2021"

1) Introduction to and exploration of the data

The data used for this exercise is derived from a study exploring the relationship between learning approaches and student’s achievements in an introductory statistics course in Finland conducted during years 2014 and 2015. Students in an introductory statistics course filled in a questionnaire exploring their learning approaches and study skills. The student’s achievements on the course were measured by the points they received in the exams. Only a part of the original data will be used in this exercise and is explored below. This smaller data set is in a data frame called learning2014.

# import the data 
learning2014 <- read.table("./Data/learning2014.txt", sep = "\t")

# structure of the data frame
str(learning2014) 
## 'data.frame':    166 obs. of  7 variables:
##  $ gender  : chr  "F" "M" "F" "M" ...
##  $ age     : int  53 55 49 53 49 38 50 37 37 42 ...
##  $ attitude: num  3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
##  $ deep    : num  3.58 2.92 3.5 3.5 3.67 ...
##  $ stra    : num  3.38 2.75 3.62 3.12 3.62 ...
##  $ surf    : num  2.58 3.17 2.25 2.25 2.83 ...
##  $ points  : int  25 12 24 10 22 21 21 31 24 26 ...
colSums(is.na(learning2014)) # number of missing values in the data
##   gender      age attitude     deep     stra     surf   points 
##        0        0        0        0        0        0        0

There are 166 observations by 7 variables and no missing data in the data set.

Variables age and gender are self-explanatory, but the other 5 variables are explained below:

  • attitude: student’s attitude towards statistics
  • surf: surface approach for learning — memorizing without understanding (lack of purpose, unrelated memorizing)
  • deep: deep approach for learning — intention to maximize understanding (relating ideas, use of evidence)
  • stra: strategic approach for learning — maximizing the chance of achieving the highest possible grades (organized studying and time management)
  • points: points received in the exams of the course (measure of student’s achievements)

Explanations for the variables are derived from here.

Graphical overview of the data

# first upload the libraries
library(ggplot2)
library(GGally)
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
# now the graph
ggpairs(learning2014, mapping = aes(col = gender, alpha = 0.5), 
        lower = list(combo = wrap("facethist", bins = 20)))

# summaries of the variables in the data
summary(learning2014)
##     gender               age           attitude          deep      
##  Length:166         Min.   :17.00   Min.   :1.400   Min.   :1.583  
##  Class :character   1st Qu.:21.00   1st Qu.:2.600   1st Qu.:3.333  
##  Mode  :character   Median :22.00   Median :3.200   Median :3.667  
##                     Mean   :25.51   Mean   :3.143   Mean   :3.680  
##                     3rd Qu.:27.00   3rd Qu.:3.700   3rd Qu.:4.083  
##                     Max.   :55.00   Max.   :5.000   Max.   :4.917  
##       stra            surf           points     
##  Min.   :1.250   Min.   :1.583   Min.   : 7.00  
##  1st Qu.:2.625   1st Qu.:2.417   1st Qu.:19.00  
##  Median :3.188   Median :2.833   Median :23.00  
##  Mean   :3.121   Mean   :2.787   Mean   :22.72  
##  3rd Qu.:3.625   3rd Qu.:3.167   3rd Qu.:27.75  
##  Max.   :5.000   Max.   :4.333   Max.   :33.00

The number of females is almost twice the number of males in the data, but there seems to be no significant difference between the females and males, except a slightly lower values in attitude seen in females compared to males (see the box plots on the top panel in the paired plot). However, this might be due to the lower number of male participants in the data. The age is between 17 – 55, but most of the participants fall below age 30. The rest of the variables (attitude, deep, stra, surf, points) seem to be close to normal distribution. Variables points and attitude correlate positively, while there is slight negative correlation between deep and surf. This negative correlation is only seen in the male participants.

2) Regression model

We will use regression analysis to see if we could build a model to predict points from the other variables. The dependent variable (response variable) here is points and we will choose three possible explanatory variables to start building the model. The three explanatory variables will be attitude, stra and deep.

# We will start building the model using three explanatory variables
M1 <- lm(points ~ 1 + attitude + stra + deep, data = learning2014)
# Show a summary of the fitted model
summary(M1)
## 
## Call:
## lm(formula = points ~ 1 + attitude + stra + deep, data = learning2014)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -17.5239  -3.4276   0.5474   3.8220  11.5112 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.3915     3.4077   3.343  0.00103 ** 
## attitude      3.5254     0.5683   6.203 4.44e-09 ***
## stra          0.9621     0.5367   1.793  0.07489 .  
## deep         -0.7492     0.7507  -0.998  0.31974    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.289 on 162 degrees of freedom
## Multiple R-squared:  0.2097, Adjusted R-squared:  0.195 
## F-statistic: 14.33 on 3 and 162 DF,  p-value: 2.521e-08

According to the model summary, attitude shows a significant relationship with points in the model, meaning that attitude could be used to predict points. Together attitude, stra and deep explain 20.97% of points (this information is derived from the multiple R-squared).

Since stra and deep did not show significant relationship with points a new model is build by using the significant explanatory variable attitude only.

M2 <- lm(points ~ 1 + attitude, data = learning2014)

summary(M2)
## 
## Call:
## lm(formula = points ~ 1 + attitude, data = learning2014)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -16.9763  -3.2119   0.4339   4.1534  10.6645 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.6372     1.8303   6.358 1.95e-09 ***
## attitude      3.5255     0.5674   6.214 4.12e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared:  0.1906, Adjusted R-squared:  0.1856 
## F-statistic: 38.61 on 1 and 164 DF,  p-value: 4.119e-09

Variable attitude explains 19.06% of points and this explanatory variable remains significant.

Next we can do model validation by drawing few diagnostic plots. Let’s focus on residuals vs fitted values, normal QQ-plot and residuals vs leverage.

par(mfrow=c(1,3)) # makes the plots appear in a 1x3 window
plot(M2, which = c(1,2,5)) # 1: residuals vs fitted # 2: normal QQ-plot # 5: residuals vs leverage

Plot: residuals vs fitted

According to this plot, the fitted regression model seems to be appropriate. The residuals are spread randomly in the plot, indicating that the errors do not depend on the explanatory variable.

Plot: normal Q-Q

The plot indicates that the errors of the model are normally distributed, since most of the residuals follow linearity.

Plot: residuals vs leverage

No single observation stands out in the plot, implicating that single observations do not have unreasonably high impact on the model.



Week 3: Logistic regression

date()
## [1] "Fri Nov 26 19:41:27 2021"

1) Introduction and exploration of the data

The data explores student achievement in maths and Portuguese language at the secondary education level in two Portuguese schools. The data was downloaded from here and modified for this exercise.

# import the data 
students_poma <- read.table("./Data/student-portmath.txt", sep = "\t")

# dimensions 
dim(students_poma)
## [1] 370  51
# variable names
names(students_poma) 
##  [1] "school"     "sex"        "age"        "address"    "famsize"   
##  [6] "Pstatus"    "Medu"       "Fedu"       "Mjob"       "Fjob"      
## [11] "reason"     "guardian"   "traveltime" "studytime"  "schoolsup" 
## [16] "famsup"     "activities" "nursery"    "higher"     "internet"  
## [21] "romantic"   "famrel"     "freetime"   "goout"      "Dalc"      
## [26] "Walc"       "health"     "n"          "id.p"       "id.m"      
## [31] "failures"   "paid"       "absences"   "G1"         "G2"        
## [36] "G3"         "failures.p" "paid.p"     "absences.p" "G1.p"      
## [41] "G2.p"       "G3.p"       "failures.m" "paid.m"     "absences.m"
## [46] "G1.m"       "G2.m"       "G3.m"       "alc_use"    "high_use"  
## [51] "cid"

The data has 370 observations by 51 variables, including binary and numeric variables. Find more information about the variables here. Separate data sets for maths and Portuguese language classes were merged and at the same time a number of variables were added to the data. Variables with suffix .p are specific for performance in Portuguese language, and with suffix .m in maths. Variable alc_use is the average of Dalc and Walc and variable high_use is ‘TRUE’ if alc_use is higher than 2.

We will to study the relationship between high/low alcohol consumption and some of the variables. Let’s choose four variables for the purpose: sex, absences, failures and G3. I’m hypothesizing that high alcohol consumption leads to increased occasions of absences and failures in the classes and lower grades in the final exam (G3). Sex might also have an impact on alcohol consumption, and I’m guessing that males show more often high alcohol consumption compared to females.

Let’s explore the distributions and relationships between these four variables and high/low alcohol consumption next.

# load the libraries
library(ggplot2)
library(GGally)
library(ggpubr)

# make a new data frame including only the variables you're interested in 
my_var <- c("high_use", "sex", "failures", "absences", "G3")
poma_4var <- students_poma[,my_var]

# high/low alcohol consumption by sex
table(high_use = poma_4var$high_use, sex = poma_4var$sex)
##         sex
## high_use   F   M
##    FALSE 154 105
##    TRUE   41  70
# fraction failures by student high/low alcohol consumption
mosaicplot(table(poma_4var$failures, poma_4var$high_use), main = "Number of failures by high/low alcohol consumption", xlab = "Number of failures", ylab = "High alcohol consumption", color = T)

# plot number of absences by high/low alcohol consumption
p1 <- ggplot(poma_4var, aes(x = high_use, y = absences, fill = high_use)) + 
            geom_boxplot() + theme_minimal() + xlab("") + ylab("Absences")

# plot final grade by high/low alcohol consumption
p2 <- ggplot(poma_4var, aes(x = high_use, y = G3, fill = high_use)) +
            geom_boxplot() + theme_minimal() + xlab("") + ylab("Final grade")

# plot the box plots together
ggarrange(p1, p2, ncol = 2, common.legend = T)

High alcohol consumption is more common in males compared to females. The frequency of failures also appears greater in proportion with high alcohol consumption compared to low. The number of absences is higher more often in students who consume high amounts of alcohol compared to the students who consume low amounts. Most of the low alcohol consumption students have been absent less than five times, when for most of the high alcohol consumption student this is less than 10. Finally, low alcohol consuming students achieve more often higher grades from the final exam compared to the high alcohol consuming students. After exploring the data, the hypothesis of high alcohol consumption leading to higher number of failures and absences and eventually lower final grades seems to hold, but the significance of this relationship is yet to be studied.

2) Logistic regression

We will use logistic regression to statistically explore the relationship between high/low alcohol consumption and sex, absences, failures and G3 (final grade).

# let's first change variable 'sex' from character to factor
poma_4var$sex <- as.factor(poma_4var$sex)

# next compute the logistic regression model
M1 <- glm(high_use ~ sex + failures + absences + G3, data = poma_4var, family = "binomial")

# model summary
summary(M1)
## 
## Call:
## glm(formula = high_use ~ sex + failures + absences + G3, family = "binomial", 
##     data = poma_4var)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.1561  -0.8429  -0.5872   1.0033   2.1393  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.38733    0.51617  -2.688  0.00719 ** 
## sexM         1.00870    0.24798   4.068 4.75e-05 ***
## failures     0.50382    0.22018   2.288  0.02213 *  
## absences     0.09058    0.02322   3.901 9.56e-05 ***
## G3          -0.04671    0.03948  -1.183  0.23671    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 452.04  on 369  degrees of freedom
## Residual deviance: 405.59  on 365  degrees of freedom
## AIC: 415.59
## 
## Number of Fisher Scoring iterations: 4
# compute odds ratios and confident intervals
OR <- coef(M1) %>% exp
CI <- confint(M1) %>% exp
## Waiting for profiling to be done...
cbind(OR, CI) # prints out the ORs with their CIs
##                    OR      2.5 %    97.5 %
## (Intercept) 0.2497422 0.08880747 0.6760545
## sexM        2.7420380 1.69666006 4.4943946
## failures    1.6550376 1.08094265 2.5808643
## absences    1.0948038 1.04844539 1.1486025
## G3          0.9543647 0.88291082 1.0311936

The logistic regression model suggests that males have significantly higher probability for high alcohol consumption compared to females. Students showing high alcohol consumption are also more likely to fail in the classes and be absent from the school. These results were significant. However, high alcohol consumption is not affecting the final grade. The odds ratio for sex indicates a student showing high alcohol consumption is 2.7 times more likely to be male. The odds ratios indicate that a person is 1.65 times more likely to fail a class and 1.1 times more likely to be absent if their alcohol consumption is high.

Let’s modify the model so that it includes only the variables that showed statistically significant relationship with high/low alcohol consumption. Then we will explore the predictive power of this model.

# make a new model
M2 <- glm(high_use ~ sex + failures + absences, data = poma_4var, family = "binomial")

summary(M2)
## 
## Call:
## glm(formula = high_use ~ sex + failures + absences, family = "binomial", 
##     data = poma_4var)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.1550  -0.8430  -0.5889   1.0328   2.0374  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -1.94150    0.23129  -8.394  < 2e-16 ***
## sexM         0.99731    0.24725   4.034 5.49e-05 ***
## failures     0.59759    0.20698   2.887  0.00389 ** 
## absences     0.09245    0.02323   3.979 6.91e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 452.04  on 369  degrees of freedom
## Residual deviance: 406.99  on 366  degrees of freedom
## AIC: 414.99
## 
## Number of Fisher Scoring iterations: 4
# predictive model
# predict the probability of high alcohol consumption
probs <- predict(M2, type = "response")

# add the predicted probabilities to your data set
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
poma_4var <- mutate(poma_4var, probability = probs)

# use the probabilities to predict high alcohol consumption
poma_4var <- mutate(poma_4var, predictions = probability > 0.5)

# print predictions vs actual values
table(high_use = poma_4var$high_use, prediction = poma_4var$prediction)
##         prediction
## high_use FALSE TRUE
##    FALSE   252    7
##    TRUE     78   33
# show the same in a plot
p3 <- ggplot(poma_4var, aes(x = high_use, y = predictions))
p3 + geom_point(position = "jitter")

# compute the proportion of inaccurately classified individuals
# define a loss function (mean prediction error)
loss_func <- function(class, prob) {
  n_wrong <- abs(class - prob) > 0.5
  mean(n_wrong)
}

# call loss_func to compute the average number of wrong predictions in the data
loss_func(class = poma_4var$high_use, prob = 0)
## [1] 0.3

The model classifies 30% of the individuals inaccurately. This inaccuracy is best seen in classifying more student to not have high alcohol consumption as compared to the true values (see the plot).


Week 4: Clustering and classification

date()
## [1] "Fri Nov 26 19:41:29 2021"

This week we will use the data set Boston provided in the R package MASS. The R documentation file for the data can be found here.

# load the data 
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
# dimensions
dim(Boston) # 506 observations by 14 variables
## [1] 506  14
# structure
str(Boston) # a data.frame containing numerical data
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
# two of the variables are integers, let's check their unique values
unique(Boston$chas)
## [1] 0 1
unique(Boston$rad)
## [1]  1  2  3  5  4  8  6  7 24

1) Overview of the data

# load libraries
library(ggplot2)
library(GGally)

# graphical overview of the data
ggpairs(Boston, upper = list(continuous = wrap("cor", size=4)))

# summaries
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

Most of the variables are continuous data, except chas and rad which are integers. The variables have different distributions and only rm shows normal distribution. Variables indus and tax show bimodal distribution, with most of the values falling in the low or the high end of the scale, and less in the middle. Variables crim, zn, nox, dis, lstat and medv are more or less left-skewed whereas variables age, pratio and black are right-skewed. There is strong positive correlation between many of the variables, as between rm and medv, and between nox and age, and strong negative correlation between as between rm and lstat, and between lstat and medv.

2) Modifing the data set

# standardize the data
boston_scaled <- as.data.frame(scale(Boston))

summary(boston_scaled)
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865

The data was standardized by scaling the variables, that is, the column means were subtracted from the corresponding columns and the difference divided by standard deviation. Now the values span between negative and positive, and the difference between the minimum and the maximum value is not as great. Next we will make variable crim into a categorical variable and divide the data set into a training set and a test set.

# load dplyr
library(dplyr)

# create categories out of the numerical vector and use the quantiles as break points
bins <- quantile(boston_scaled$crim)

# create categorical variable 'crime' out of 'bins'
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = T)

# replace 'crim' with the categorical variable 'crime'
boston_scaled <- dplyr::select(boston_scaled, -crim) # remove 'crim'
boston_scaled <- data.frame(boston_scaled, crime) # add 'crime'

names(boston_scaled) # check the variable names again
##  [1] "zn"      "indus"   "chas"    "nox"     "rm"      "age"     "dis"    
##  [8] "rad"     "tax"     "ptratio" "black"   "lstat"   "medv"    "crime"
# create training data set using 80% of the data
n <- nrow(boston_scaled) # number of rows in the data set
n80 <- sample(n, size = n * 0.8) # randomly choose 80% of the rows
train <- boston_scaled[n80,] # training set

# create test data set
test <- boston_scaled[-n80,] 

3) Linear discriminant analysis

We will fit a linear discriminant analysis (LDA) on the train set and use crime as the target variable. All the other variables are predictor variables in the analysis. The crime categories will be predicted from the test data set using the LDA model.

# linear discriminant analysis fit
lda.fit <- lda(crime ~ ., data = train)

# draw a biplot
# function for the biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "orange", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# change the 'crime' classes to numeric
classes <- as.numeric(train$crime)

# draw the plot
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1) # add the arrows

# save the 'crime' categories from the test set and remove the variable from the set
crime_categs <- test$crime # save the crime categories into a new object
test <- dplyr::select(test, -crime) # remove variable crime 

# predict the crime categories in the test set
lda.pred <- predict(lda.fit, newdata = test)

# the results
table(correct = crime_categs, predicted = lda.pred$class)
##                  predicted
## correct           [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
##   [-0.419,-0.411]              13             11               1              0
##   (-0.411,-0.39]                7             19               3              0
##   (-0.39,0.00739]               0             11              15              1
##   (0.00739,9.92]                0              0               1             20

The LDA model fitted using 80% of the original data set performs quite well in predicting the categories of the crime variable. The lowest and the highest crime rates best predicted, but the two categories between these rates are not as easily correctly predicted by the LDA model.

4) Clustering

# reload the Boston data set
data('Boston')

# scale the data
boston_scaled_2 <- scale(Boston)

# calculate distance between the observations
dist_eu <- dist(boston_scaled_2, method = "euclidean")

# k-means clustering
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
set.seed(12345)
fviz_nbclust(boston_scaled_2, kmeans, method = "wss") # find the optimal amount of clusters

km <- kmeans(Boston, centers = 3) # optimal number of clusters is 3
km # print the output
## K-means clustering with 3 clusters of sizes 38, 102, 366
## 
## Cluster means:
##         crim       zn     indus       chas       nox       rm      age      dis
## 1 15.2190382  0.00000 17.926842 0.02631579 0.6737105 6.065500 89.90526 1.994429
## 2 10.9105113  0.00000 18.572549 0.07843137 0.6712255 5.982265 89.91373 2.077164
## 3  0.3749927 15.71038  8.359536 0.07103825 0.5098626 6.391653 60.41339 4.460745
##        rad      tax  ptratio     black    lstat     medv
## 1 22.50000 644.7368 19.92895  57.78632 20.44868 13.12632
## 2 23.01961 668.2059 20.19510 371.80304 17.87402 17.42941
## 3  4.45082 311.2322 17.81776 383.48981 10.38866 24.93169
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 
##   3   3   1   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   1   1   3   3   3 
## 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   2   2   2   2 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 
##   2   2   2   2   2   2   2   1   2   2   2   2   2   2   2   2   2   2   2   2 
## 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 
##   2   2   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   1   1   1 
## 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 
##   2   2   2   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2 
## 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 
##   2   2   2   2   2   1   2   2   2   2   1   2   2   2   1   1   1   1   2   2 
## 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 
##   2   2   2   2   2   2   1   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   3   3   3   3   3   3   3 
## 501 502 503 504 505 506 
##   3   3   3   3   3   3 
## 
## Within cluster sum of squares by cluster:
## [1]  313208.7  181891.7 2573399.1
##  (between_SS / total_SS =  84.2 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"
# plot the clusters in a pair plot
ggpairs(Boston, mapping = aes(col = as.factor(km$cluster), alpha = 0.5),
        upper = list(continuous = wrap("cor", size = 4)))

Cluster 3 (blue points) seems to divert from the other two clusters (green and red points).

(more chapters to be added similarly as we proceed with the course!)